<template>
  <view class="interviewing-page">
    <view class="top-bar">
      <text class="job">{{ interviewInfo.position || '面试' }}</text>
      <text class="timer">{{ formatTime(remainingTime) }}</text>
    </view>
    <view class="video-area">
      <view class="avatar-box">
        <image class="interviewer-avatar" :src="interviewInfo.interviewer?.avatar" mode="aspectFill"></image>
      </view>
      <view class="video-tip">数字人面试官正在提问。</view>
      <view class="self-video">本人视频画面</view>
    </view>
    <view class="question-area">
      <view class="q-title">问题 {{ currentQuestionIndex + 1 }}/{{ questions.length }}</view>
      <view class="q-content">{{ currentQuestion?.title }}</view>
      <view class="q-desc" v-if="currentQuestion?.description">{{ currentQuestion.description }}</view>
      <view class="progress-bar">
        <view class="progress-inner" :style="{width: progressWidth + '%'}"></view>
      </view>
      <view class="q-progress">已回答: {{ answeredCount }}题  剩余: {{ remainingCount }}题</view>
    </view>
    <!-- 悬浮窗本人视频画面 -->
    <view
      class="self-video-float"
      :style="{ left: floatPos.x + 'px', top: floatPos.y + 'px' }"
      @touchstart="onFloatStart"
      @touchmove="onFloatMove"
      @touchend="onFloatEnd"
    >
      本人视频画面
    </view>
    <view class="answer-area">
      <textarea class="answer-input" 
                v-model="currentAnswer" 
                placeholder="请在此输入您的答案…" 
                :disabled="isSubmitting"
                maxlength="1000" />
      <button class="submit-btn" 
              @click="submitAnswer"
              :disabled="isSubmitting || !currentAnswer.trim()">
        {{ isSubmitting ? '提交中...' : '提交答案' }}
      </button>
    </view>
  </view>
</template>

<script>
import request from '../../utils/request'

// 面试状态常量
const INTERVIEW_STATUS = {
  NOT_STARTED: 1,    // 未开始
  IN_PROGRESS: 2,    // 面试中
  COMPLETED: 3       // 面试完成
}

// 面试结果常量
const INTERVIEW_RESULT = {
  FAILED: 0,         // 未通过
  PENDING: 1,        // 待定
  PASSED: 2          // 通过
}

export default {
  data() {
    return {
      interviewInfo: {},
      questions: [],
      currentQuestionIndex: 0,
      currentAnswer: '',
      isSubmitting: false,
      remainingTime: 0, // 剩余时间（秒）
      timer: null,
      answers: [], // 存储已提交的答案
      candidateInfo: {}, // Added to store candidateInfo
      floatPos: { x: 250, y: 400 }, // 默认位置
      dragging: false,
      dragStart: { x: 0, y: 0 },
    }
  },
  computed: {
    currentQuestion() {
      return this.questions[this.currentQuestionIndex] || null;
    },
    answeredCount() {
      return this.answers.length;
    },
    remainingCount() {
      return this.questions.length - this.answeredCount;
    },
    progressWidth() {
      return (this.answeredCount / this.questions.length) * 100;
    }
  },
  onLoad() {
    this.loadInterviewInfo();
    this.startTimer();
  },
  onUnload() {
    this.stopTimer();
  },
  methods: {
    // 加载面试信息
    async loadInterviewInfo() {
      try {
        const candidateInfo = uni.getStorageSync('candidateInfo');
        if (!candidateInfo || !candidateInfo.id) {
          uni.showToast({
            title: '未找到候选人信息',
            icon: 'none'
          });
          return;
        }

        console.log('开始获取面试信息，候选人ID:', candidateInfo.id);
        const res = await request.get(`/api/candidate/interview/${candidateInfo.id}`);
        console.log('获取面试信息响应:', res);

        if (res.code === 200) {
          const data = res.data;

          // **使用后端返回的最新候选人信息更新本地存储和组件数据**
          if (data.candidateInfo) {
              this.candidateInfo = data.candidateInfo; // 更新组件数据
              uni.setStorageSync('candidateInfo', data.candidateInfo); // 更新本地存储
          } else {
              // 如果后端没有返回 candidateInfo，尝试使用本地存储的但可能不是最新的
              // 注意：这里保留旧逻辑作为备选，但最佳实践是后端始终返回最新状态
              // this.candidateInfo = candidateInfoFromStorage;
          }

          // 设置面试信息（position 可能需要从 schedule 中获取）
          this.interviewInfo = {
            position: data.schedule?.positionId, // 或者从后端返回的 candidateInfo 中获取 position
            interviewer: data.interviewer,
            duration: data.schedule?.duration
          };
          
          // 设置题目列表
          if (data.questions && Array.isArray(data.questions)) {
            this.questions = data.questions.map(q => ({
              id: q.id,
              title: q.title,
              description: q.description,
              difficulty: q.difficulty
            }));
          }
          
          // 设置面试时长（分钟转秒）
          if (data.schedule?.duration) {
            this.remainingTime = data.schedule.duration * 60;
          }

          // **使用更新后的（来自后端返回的）candidateInfo.interviewStatus 进行校验**
          if (this.candidateInfo.interviewStatus !== INTERVIEW_STATUS.IN_PROGRESS) { // INTERVIEW_STATUS.IN_PROGRESS 是 2
            console.log('面试状态不正确，当前状态:', this.candidateInfo.interviewStatus);
            uni.showToast({
              title: '当前面试状态不正确',
              icon: 'none'
            });
            uni.navigateBack(); // 返回面试首页或其他合适页面
            return; // 终止后续逻辑
          }

          // 如果状态正确，继续面试中的逻辑
          console.log('面试状态正确，开始面试页面逻辑');
        } else {
          console.error('获取面试信息失败响应:', res.msg);
          uni.showToast({
            title: res.msg || '获取面试信息失败',
            icon: 'none'
          });
          uni.navigateBack(); // 获取详情失败也返回
        }
      } catch (error) {
        console.error('获取面试信息失败:', error);
        uni.showToast({
          title: '获取面试信息失败，请稍后重试',
          icon: 'none'
        });
      }
    },
    // 提交答案
    async submitAnswer() {
      if (!this.currentAnswer.trim() || this.isSubmitting) {
        return;
      }

      this.isSubmitting = true;
      try {
        const candidateInfo = uni.getStorageSync('candidateInfo');
        const answer = {
          questionId: this.currentQuestion.id,
          answer: this.currentAnswer.trim()
        };

        console.log('提交答案:', answer);
        const res = await request.post(`/candidate/interview/answer/${candidateInfo.id}`, answer);
        console.log('提交答案响应:', res);

        if (res.code === 200) {
          // 保存答案
          this.answers.push({
            questionId: this.currentQuestion.id,
            answer: this.currentAnswer.trim()
          });

          // 清空当前答案
          this.currentAnswer = '';

          // 检查是否还有下一题
          if (this.currentQuestionIndex < this.questions.length - 1) {
            this.currentQuestionIndex++;
          } else {
            // 所有题目都已完成，跳转到结果页
            this.completeInterview();
          }
        } else {
          uni.showToast({
            title: res.msg || '提交答案失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('提交答案失败:', error);
        uni.showToast({
          title: '提交答案失败，请稍后重试',
          icon: 'none'
        });
      } finally {
        this.isSubmitting = false;
      }
    },
    // 完成面试
    async completeInterview() {
      try {
        const candidateInfo = uni.getStorageSync('candidateInfo');
        console.log('完成面试，候选人ID:', candidateInfo.id);
        const res = await request.post(`/api/candidate/interview/complete/${candidateInfo.id}`);
        console.log('完成面试响应:', res);

        if (res.code === 200) {
          // 跳转到结果页
          uni.redirectTo({
            url: `/pages/result/result?id=${candidateInfo.id}`
          });
        } else {
          uni.showToast({
            title: res.msg || '完成面试失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('完成面试失败:', error);
        uni.showToast({
          title: '完成面试失败，请稍后重试',
          icon: 'none'
        });
      }
    },
    // 开始计时器
    startTimer() {
      this.timer = setInterval(() => {
        if (this.remainingTime > 0) {
          this.remainingTime--;
        } else {
          this.stopTimer();
          // 时间到，自动完成面试
          this.completeInterview();
        }
      }, 1000);
    },
    // 停止计时器
    stopTimer() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    // 格式化时间
    formatTime(seconds) {
      const minutes = Math.floor(seconds / 60);
      const remainingSeconds = seconds % 60;
      return `${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`;
    },
    onFloatStart(e) {
      this.dragging = true;
      this.dragStart = {
        x: e.touches[0].clientX - this.floatPos.x,
        y: e.touches[0].clientY - this.floatPos.y
      };
    },
    onFloatMove(e) {
      if (!this.dragging) return;
      this.floatPos = {
        x: e.touches[0].clientX - this.dragStart.x,
        y: e.touches[0].clientY - this.dragStart.y
      };
    },
    onFloatEnd() {
      this.dragging = false;
    },
  }
}
</script>

<style>
.interviewing-page {
  min-height: 100vh;
  background: #f6f7fb;
  padding: 0 24rpx 40rpx 24rpx;
  display: flex;
  flex-direction: column;
}

.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 32rpx 0 24rpx 0;
}

.job {
  font-size: 30rpx;
  font-weight: bold;
  color: #3a6cff;
}

.timer {
  font-size: 28rpx;
  color: #222;
}

.video-area {
  background: #3a6cff;
  border-radius: 16rpx;
  padding: 32rpx 0 24rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 32rpx;
  color: #fff;
}

.avatar-box {
  width: 100rpx;
  height: 100rpx;
  background: #6fd6ff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 12rpx;
  overflow: hidden;
}

.interviewer-avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-tip {
  font-size: 26rpx;
  margin-bottom: 8rpx;
}

.self-video {
  font-size: 22rpx;
  opacity: 0.7;
}

.question-area {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx 20rpx;
  margin-bottom: 32rpx;
}

.q-title {
  font-size: 26rpx;
  color: #3a6cff;
  font-weight: bold;
  margin-bottom: 8rpx;
}

.q-content {
  font-size: 24rpx;
  color: #333;
  margin-bottom: 16rpx;
  line-height: 1.6;
}

.q-desc {
  font-size: 22rpx;
  color: #888;
  margin-bottom: 16rpx;
}

.progress-bar {
  width: 100%;
  height: 8px;
  background: #e0eaff;
  border-radius: 4px;
  margin-bottom: 8rpx;
  overflow: hidden;
}

.progress-inner {
  height: 100%;
  background: #3a6cff;
  border-radius: 4px;
  transition: width 0.3s;
}

.q-progress {
  font-size: 22rpx;
  color: #888;
  margin-top: 8rpx;
}

.answer-area {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx 20rpx;
  margin-bottom: 32rpx;
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.answer-input {
  min-height: 80px;
  border: 1px solid #e5e5e5;
  border-radius: 8px;
  padding: 10px;
  font-size: 16px;
  resize: vertical;
  margin-bottom: 8px;
}

.answer-input:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.submit-btn {
  width: 100%;
  height: 44px;
  background: #3a6cff;
  color: #fff;
  font-size: 18px;
  font-weight: bold;
  border: none;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(58,108,255,0.08);
}

.submit-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.self-video-float {
  position: fixed;
  width: 120px;
  height: 90px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #333;
  user-select: none;
}
</style> 